package com.panghl.controller;

import com.panghl.domain.ResponseResult;
import com.panghl.domain.User;
import com.panghl.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author panghl
 * @Date 2022/2/12
 * @Description 自定义登录接口
 **/
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        //登录
        return loginService.login(user);
    }

    /**
     * 可以用过注销处理器 SGLogoutSuccessHandler 处理
     * @return
     */
    @RequestMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

    /**
     * 测试登录
     */
    @GetMapping("/article")
    public ResponseResult article() {
        Subject subject = SecurityUtils.getSubject();
        // 登录了返回true
        if (subject.isAuthenticated()) {
            return new ResponseResult(HttpStatus.OK.value(), "您已经登录了(You are already logged in)", null);
        } else {
            return new ResponseResult(HttpStatus.OK.value(), "你是游客(You are guest)", null);
        }
    }

    /**
     * 测试登录注解(@RequiresAuthentication和subject.isAuthenticated()返回true一个性质)
     */
    @GetMapping("/article2")
    @RequiresAuthentication
    public ResponseResult requireAuth() {
        return new ResponseResult(HttpStatus.OK.value(), "您已经登录了(You are already logged in)", null);
    }

    /**
     * 测试授权
     */
    @GetMapping("/article3")
    @RequiresAuthentication
    @RequiresPermissions("admin:add")
    public ResponseResult requireAuth2() {
        return new ResponseResult(HttpStatus.OK.value(), "您已经有admin:add权限", null);
    }


    @GetMapping("/noauth")
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }
}
